<template>
  <div class="node-properties-panel">
    <a-card
      :title="panelTitle"
      size="small"
      :bordered="false"
      class="properties-card"
      v-show="selectedNode"
    >
      <template #extra>
        <a-button
          type="text"
          size="small"
          @click="closePanel"
          :icon="h(CloseOutlined)"
        />
      </template>

      <!-- 节点基本信息 -->
      <div class="node-basic-info" v-if="selectedNode">
        <div class="info-item">
          <span class="label">节点ID：</span>
          <span class="value">{{ selectedNode.id }}</span>
        </div>
        <div class="info-item">
          <span class="label">节点名称：</span>
          <span class="value">{{ selectedNode.name || selectedNode.label || '未知' }}</span>
        </div>
        <div class="info-item" v-if="selectedNode.type">
          <span class="label">节点类型：</span>
          <a-tag :color="getEntityTypeColor(selectedNode.type)">
            {{ selectedNode.type }}
          </a-tag>
        </div>
        <div class="info-item" v-if="nodeDegree !== null">
          <span class="label">连接数：</span>
          <span class="value">{{ nodeDegree }}</span>
        </div>
      </div>

      <!-- 节点详细属性 -->
      <a-divider orientation="left" v-if="hasProperties">详细属性</a-divider>
      <div class="node-properties-list" v-if="hasProperties">
        <div
          class="property-item"
          v-for="(item, key) in displayProperties"
          :key="key"
        >
          <span class="property-key">{{ item.displayName }}：</span>
          <span class="property-value">{{ formatValue(item.value, key) }}</span>
        </div>
      </div>

      <!-- 无属性提示 -->
      <a-empty
        v-if="!hasProperties"
        description="暂无详细属性信息"
        :image="false"
        size="small"
      />
    </a-card>
  </div>
</template>

<script setup>
import { computed, h, ref, onMounted } from 'vue'
import { CloseOutlined } from '@ant-design/icons-vue'
import { getEntityTypeColor } from '@/apis/graph_api'
import { getSituationTypes, getDeploymentStatuses, getEquipmentCategoryLabels } from '@/apis/situation_api'

const props = defineProps({
  selectedNode: {
    type: Object,
    default: null
  },
  graphData: {
    type: Object,
    default: () => ({ nodes: [], edges: [] })
  }
})

const emit = defineEmits(['close'])

// 动态枚举映射数据
const objectTypeMapping = ref({})
const deploymentStatusMapping = ref({})
const equipmentCategoryMapping = ref({})

// 获取态势对象枚举映射
const loadSituationEnums = async () => {
  try {
    // 获取对象类型映射
    const typesRes = await getSituationTypes()
    if (typesRes.types) {
      typesRes.types.forEach(type => {
        objectTypeMapping.value[type.value] = type.label
      })
    }

    // 获取部署状态映射
    const statusesRes = await getDeploymentStatuses()
    if (statusesRes.statuses) {
      statusesRes.statuses.forEach(status => {
        deploymentStatusMapping.value[status.value] = status.label
      })
    }

    // 获取装备类别映射
    const categoryRes = await getEquipmentCategoryLabels()
    if (categoryRes.labels) {
      equipmentCategoryMapping.value = categoryRes.labels
    } else if (categoryRes.data) {
      equipmentCategoryMapping.value = categoryRes.data
    } else {
      // 直接使用返回对象作为映射
      equipmentCategoryMapping.value = categoryRes
    }
  } catch (error) {
    console.error('Failed to load situation enums:', error)
  }
}

// 组件挂载时加载枚举数据
onMounted(() => {
  loadSituationEnums()
})

// 面板标题
const panelTitle = computed(() => {
  if (!props.selectedNode) return '节点属性'
  return `节点属性 - ${props.selectedNode.name || props.selectedNode.label || props.selectedNode.id}`
})

// 计算节点连接数
const nodeDegree = computed(() => {
  if (!props.selectedNode || !props.graphData?.edges) return null

  const nodeId = props.selectedNode.id
  const degree = props.graphData.edges.reduce((count, edge) => {
    if (edge.source_id === nodeId || edge.target_id === nodeId) {
      return count + 1
    }
    return count
  }, 0)

  return degree
})

// 是否有详细属性
const hasProperties = computed(() => {
  if (!props.selectedNode) return false
  return Object.keys(displayProperties.value).length > 0
})

// 过滤并格式化显示的属性
const displayProperties = computed(() => {
  if (!props.selectedNode) return {}

  let properties = {}

  // 处理不同的数据结构
  if (props.selectedNode.properties) {
    // 如果有 properties 字段，直接使用
    properties = { ...props.selectedNode.properties }
  } else {
    // 否则使用 selectedNode 本身
    properties = { ...props.selectedNode }
  }

  // 移除已经显示在基本信息中的字段
  delete properties.id
  delete properties.name
  delete properties.label
  delete properties.type

  // 移除内部字段
  delete properties._labels
  delete properties._elementId

  // 合并扁平化的属性
  Object.keys(properties).forEach(key => {
    if (typeof properties[key] === 'object' && properties[key] !== null) {
      // 如果属性是对象，展开它的键值对
      const obj = properties[key]
      delete properties[key]
      Object.keys(obj).forEach(subKey => {
        properties[`${key}.${subKey}`] = obj[subKey]
      })
    }
  })

  // 对属性进行排序，将重要的属性放在前面
  const importantKeys = ['object_type', 'equipment_category', 'equipment_type', 'code', 'model', 'organization', 'deployment_status', 'created_at']
  const sortedProperties = {}

  // 先添加重要属性（equipment_category 优先于 equipment_type）
  importantKeys.forEach(key => {
    if (properties.hasOwnProperty(key)) {
      sortedProperties[key] = properties[key]
      delete properties[key]
    }
  })

  // 添加剩余属性
  Object.assign(sortedProperties, properties)

  // 处理特殊属性的值转换（使用动态加载的映射）
  Object.keys(sortedProperties).forEach(key => {
    if (key === 'object_type' && typeof sortedProperties[key] === 'string') {
      const typeValue = sortedProperties[key]
      sortedProperties[key] = objectTypeMapping.value[typeValue] || typeValue
    }
    if (key === 'deployment_status' && typeof sortedProperties[key] === 'string') {
      const statusValue = sortedProperties[key]
      sortedProperties[key] = deploymentStatusMapping.value[statusValue] || statusValue
    }
    if ((key === 'equipment_type' || key === 'equipment_category') && typeof sortedProperties[key] === 'string') {
      const categoryValue = sortedProperties[key]
      const mappedValue = equipmentCategoryMapping.value[categoryValue] || categoryValue
      sortedProperties[key] = mappedValue
    }
  })

  // 为属性添加中文显示名称
  const propertyNames = {
    'object_type': '对象类型',
    'equipment_type': '装备类型',
    'equipment_category': '装备类别',
    'code': '编码',
    'model': '型号',
    'organization': '组织',
    'deployment_status': '部署状态',
    'created_at': '创建时间',
    'description': '描述',
    'detection_range': '探测距离',
    'response_time': '响应时间',
    'accuracy': '精度',
    'location': '地理位置'
  }

  // 为了保持原始键名用于格式化，同时提供中文显示名
  const finalProperties = {}
  Object.keys(sortedProperties).forEach(key => {
    // 保存原始键名，但使用原始值
    finalProperties[key] = {
      value: sortedProperties[key],
      displayName: propertyNames[key] || key
    }
  })

  return finalProperties
})

// 格式化属性值的显示
const formatValue = (value, key) => {
  if (value === null || value === undefined) {
    return '无'
  }

  // 处理空字符串
  if (value === '') {
    return '无'
  }

  // 处理日期字符串
  if (typeof value === 'string' && key === 'created_at') {
    // 检查是否是 ISO 日期格式
    if (value.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)) {
      try {
        const date = new Date(value)
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch {
        return value
      }
    }
  }

  // 处理数值类型的字段，添加单位
  if (typeof value === 'number') {
    switch (key) {
      case 'detection_range':
        return `${value} km`
      case 'response_time':
        return `${value} 秒`
      case 'accuracy':
        return `${value}%`
      default:
        return String(value)
    }
  }

  if (typeof value === 'object') {
    try {
      return JSON.stringify(value, null, 2)
    } catch {
      return '[对象]'
    }
  }

  if (typeof value === 'boolean') {
    return value ? '是' : '否'
  }

  return String(value)
}

// 关闭面板
const closePanel = () => {
  emit('close')
}
</script>

<style lang="less" scoped>
.node-properties-panel {
  height: 100%;
  overflow: hidden;

  .properties-card {
    height: 100%;

    :deep(.ant-card-body) {
      height: calc(100% - 57px);
      overflow-y: auto;
      padding: 16px;
    }
  }
}

.node-basic-info {
  margin-bottom: 16px;

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    .label {
      font-weight: 500;
      color: #666;
      min-width: 80px;
      flex-shrink: 0;
    }

    .value {
      color: #333;
      word-break: break-all;
    }
  }
}

.node-properties-list {
  .property-item {
    display: flex;
    margin-bottom: 12px;
    padding: 8px 12px;
    background-color: #f8f9fa;
    border-radius: 6px;

    .property-key {
      font-weight: 500;
      color: #666;
      min-width: 100px;
      flex-shrink: 0;
    }

    .property-value {
      color: #333;
      word-break: break-all;
      white-space: pre-wrap;
      font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
      font-size: 12px;
    }
  }
}

:deep(.ant-divider-horizontal.ant-divider-with-text-left) {
  margin: 16px 0 8px 0;
}
</style>